package com.wondream.example.io.nio.chat.simple;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjun
 * @note NioChatClient
 * @date 2023-11-24  13:49
 */
public class NioChatClient {

    private SocketChannel socketChannel;

    private static final String SERVER_HOST = "127.0.0.1";

    private static final int SERVER_PORT = 8888;

    private String userName; // 聊天用户名

    public NioChatClient() throws Exception {
        // 1.客户端socket通道
        socketChannel = SocketChannel.open();
        // 2.设置非阻塞
        socketChannel.configureBlocking(false);
        // 3.初始化服务端ip和端口号
        InetSocketAddress inetSocketAddress = new InetSocketAddress(SERVER_HOST, SERVER_PORT);
        // 4.连接服务端
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("Client：没连接上，干点别的事");
            }
        }
        // 5.得到客户端地址和端口号，作为聊天用户名
        userName = socketChannel.getLocalAddress().toString().substring(1);
        info(String.format("Client (%s) is ready", userName));
    }

    // 向服务器发送消息
    public void sendMsg(String msg) throws Exception {
        if (msg.equalsIgnoreCase("bye")) {
            socketChannel.close();
            return;
        }
        msg = String.format("%s说：%s", userName, msg);
        ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
        socketChannel.write(byteBuffer);
        info(msg);
    }

    // 从服务器接收数据
    public void receiveMsg() throws Exception {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int readNum = socketChannel.read(byteBuffer);
        if (readNum<1) {
            return;
        }
        String msg = new String(byteBuffer.array(), 0, readNum);
        info(msg.trim());
    }

    private void info(String msg) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(String.format("【%s】-> %s", sdf.format(new Date()), msg)
        );
    }

    public static void main(String[] args) throws Exception {
        NioChatClient nioChatClient = new NioChatClient();
        Executors.newFixedThreadPool(1).execute(()->{
            try {
                nioChatClient.receiveMsg();
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            nioChatClient.sendMsg(msg);
        }
    }
}
